#include "kbox_array.h"
#include "kbox.h"

int arrayIndex = -1;                      
KBoxArrayItem *kboxArray = NULL;

int KBoxArrayCreate()
{
    if(kboxArray)
        return -1;

    kboxArray = (KBoxArrayItem*)KBoxMalloc(KBox_ARRAY_SIZE * sizeof(KBoxArrayItem));
    return 0;
}

void KBoxArrayDestory()
{
    if (kboxArray == NULL)
        return;

    for (int i = 0; i <= arrayIndex; i++)
    {
        KBoxFree(kboxArray[i].key);
        KBoxFree(kboxArray[i].value);
    }
    KBoxFree(kboxArray);
    kboxArray = NULL;
    arrayIndex = -1;
}

int KBoxArraySet(char *key, char *value)
{
    if (key == NULL || value == NULL || arrayIndex >= KBox_ARRAY_SIZE)
        return -1;

    int keyLen = strlen(key);
    char *kCopy = (char *)KBoxMalloc(keyLen + 1);
    if (kCopy == NULL)
        return -1;

    memset(kCopy, 0, keyLen + 1);
    strcpy(kCopy, key);

    int valueLen = strlen(value);
    char *vCopy = KBoxMalloc(valueLen + 1);
    if (vCopy == NULL)
    {
        KBoxFree(kCopy);
        return -1;
    }
    strncpy(vCopy, value, valueLen + 1);

    arrayIndex++;
    kboxArray[arrayIndex].key = kCopy;
    kboxArray[arrayIndex].value = vCopy;
    return 0;
}

int KBoxArrayDel(char *key)
{
    if (key == NULL)
        return -1;

    for (int i = 0; i <= arrayIndex; i++)
    {
        if (strcmp(kboxArray[i].key, key) == 0)
        {
            KBoxFree(kboxArray[i].key);
            KBoxFree(kboxArray[i].value);
            for (int j = i; j < arrayIndex; j++)
            {
                kboxArray[j] = kboxArray[j + 1];
            }
            arrayIndex--;
            return 0;
        }
    }
    return -1;
}

int KBoxArrayModify(char *key, char *value)
{
    if (key == NULL || value == NULL)
        return -1;

    for (int i = 0; i <= arrayIndex; i++)
    {
        if (strcmp(kboxArray[i].key, key) == 0)
        {
            KBoxFree(kboxArray[i].value);
            int valueLen = strlen(value);
            char *vCopy = KBoxMalloc(valueLen + 1);
            if (vCopy == NULL)
                return -1;
            strncpy(vCopy, value, valueLen + 1);
            kboxArray[i].value = vCopy;
            return 0;
        }
    }
    return -1;
}

char *KBoxArrayGet(char *key)
{
    if (key == NULL)
        return NULL;

    for (int i = 0; i <= arrayIndex; i++)
    {
        if (strcmp(kboxArray[i].key, key) == 0)
            return kboxArray[i].value;
    }
    return NULL;
}

void KBoxArrayError(char *message)
{
    LOG("KBoxArrayError: %s\n", message);
}


int KBoxArrayCount()
{
    return arrayIndex + 1;
}